package com.soft.javase.day12;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/5/19
 */
public class Account {
    private double balance;

    public Account(double balance) {
        this.balance = balance;
    }

    public boolean withdraw(double amount) {
        synchronized (this) {
            if (amount <= 0) {
                System.out.println(Thread.currentThread().getName() + ": 取款失败，取款金额必须大于0");
                return false;
            }

            if (balance <= 0) {
                System.out.println(Thread.currentThread().getName() + ": 取款失败，账户余额为0");
                return false;
            }


            if (balance >= amount) {
                balance -= amount;
                System.out.println(Thread.currentThread().getName() + ": 成功取款 " + amount + "，剩余余额: " + balance);
                return true;
            } else {
                System.out.println(Thread.currentThread().getName() + ": 取款失败，余额不足");
                return false;
            }
        }
    }


    public static void main(String[] args) {
        Account account = new Account(1000);
        for (int i = 1; i < 4; i++) {
            new Thread(()->{
                while(true){
                    boolean withdraw = account.withdraw(300);
                    if(!withdraw){
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"取款人"+i).start();
        }
    }
}
